package com.apinji.common.plugin;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by 轩辕夏夏 on 2017/7/14.
 */
public final class HttpUtils {
    private HttpUtils(){}

    public static String post(String apiUrl, JSONObject obj){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        StringEntity entity = null;
        try {
            entity = new StringEntity(obj.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpPost httppost = new HttpPost(apiUrl);
        entity.setContentType("application/json;charset=UTF-8");

        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //
        return result;
    }

    public static String doGet(String apiUrl){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        JSONObject obj = new JSONObject();
        HttpGet httpGet = new HttpGet(apiUrl);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
